<template>
  <div class="schedule-management">
    <van-popup v-model="showForm" position="top" :style="{ height: '15%' }">

      <div style="position:fixed;z-index:1;width:100%; top:50px;left:0;">
        <!--      <div class="van-search" style="position:fixed;z-index:1;width:15vw;left:0vw;top:1vh;font-size:14px;line-height:34px;background:rgb(255,255,255);"><van-icon @click="returnHome" name="home-o" size="25px" /></div>-->
        <form action="/">
          <van-search v-if="this.idobject == 'dailyreports' || this.idobject == 'weekreports' || this.idobject == 'monthreport1'" placeholder="请输入人员名称" v-model="sval" clearable show-action @search="onSearch" @clear="onCancel" style="position:fixed;top:0vh;left:0vw;width:85vw;z-index:1">
            <template #action>
              <div style="color: #ff4d4f" @click="onSearch">搜索</div>
            </template>
          </van-search>
          <van-search :placeholder="`请输入${searchPh}`" v-model="sval" clearable show-action @search="onSearch" @clear="onCancel" style="position:fixed;top:0vh;left:0vw;width:85vw;z-index:1">
            <template #action>
              <div style="color: #ff4d4f" @click="onSearch">搜索</div>
            </template>
          </van-search>
        </form>
      </div>
    </van-popup>

    <van-popup v-model="searchshow" position="right" style="width:90vw;height:100vh">
      <div style="padding-top:60px;padding-left:1vw;padding-right:1vw;">
        <form action="">
          <!--<van-field clearable v-for="condition in conditiondata" :key="condition.viewcondition_id" v-model="condition.viewcondition_value" :label="condition.viewcondition_title"/>-->
          <template v-if="searchshow && conditiondata.length > 0">
            <van-tree-select height="55vh" :items="items" :main-active-index.sync="mainactive">
              mainactive: 0,
              <template #content>
                <van-radio-group v-model="conditiondata[mainactive].viewcondition_uitype" v-if="conditiondata[mainactive].viewcondition_uitype === 'int' || conditiondata[mainactive].viewcondition_uitype === 'double' || conditiondata[mainactive].viewcondition_uitype === 'money' || conditiondata[mainactive].viewcondition_uitype === 'percent'">
                  <van-cell-group>
                    <van-cell title="等于" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'eq'">
                      <template #right-icon>
                        <van-radio name="eq" />
                      </template>
                    </van-cell>
                    <van-cell title="!=" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'noteq'">
                      <template #right-icon>
                        <van-radio name="noteq" />
                      </template>
                    </van-cell>
                    <van-cell title="大于" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'bt'">
                      <template #right-icon>
                        <van-radio name="bt" />
                      </template>
                    </van-cell>
                    <van-cell title="大于等于" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'bteq'">
                      <template #right-icon>
                        <van-radio name="bteq" />
                      </template>
                    </van-cell>
                    <van-cell title="小于" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'lt'">
                      <template #right-icon>
                        <van-radio name="lt" />
                      </template>
                    </van-cell>
                    <van-cell title="小于等于" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'lteq'">
                      <template #right-icon>
                        <van-radio name="lteq" />
                      </template>
                    </van-cell>
                    <van-cell title="空" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'empty'">
                      <template #right-icon>
                        <van-radio name="empty" />
                      </template>
                    </van-cell>
                    <van-cell title="非空" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'notempty'">
                      <template #right-icon>
                        <van-radio name="notempty" />
                      </template>
                    </van-cell>
                  </van-cell-group>
                </van-radio-group>
                <van-radio-group v-model="conditiondata[mainactive].viewcondition_comparison" v-else-if="conditiondata[mainactive].viewcondition_uitype === 'bool'">
                  <van-cell-group>
                    <van-cell title="=" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'eq'">
                      <template #right-icon>
                        <van-radio name="eq" />
                      </template>
                    </van-cell>
                    <van-cell title="!=" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'noteq'">
                      <template #right-icon>
                        <van-radio name="noteq" />
                      </template>
                    </van-cell>
                    <van-cell title="空" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'empty'">
                      <template #right-icon>
                        <van-radio name="empty" />
                      </template>
                    </van-cell>
                    <van-cell title="非空" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'notempty'">
                      <template #right-icon>
                        <van-radio name="notempty" />
                      </template>
                    </van-cell>
                  </van-cell-group>
                </van-radio-group>
                <van-radio-group v-model="conditiondata[mainactive].viewcondition_comparison" v-else-if="conditiondata[mainactive].viewcondition_uitype === 'datetime'">
                  <van-cell-group>
                    <!--                        <van-cell    :value="date" v-model="conditiondata[mainactive].viewcondition_value" title="选择单个日期"  @click="calendarShow = true" />-->
                    <!--                        <van-calendar  v-model="calendarShow" :show-confirm="false" position="right"  @confirm="onCalendarConfirm"  />-->

                    <van-cell title="等于" clickable @click="setValueForDatetime('eq')">
                      <template #right-icon>
                        <van-radio name="eq" />
                      </template>
                    </van-cell>

                    <van-cell title="大于" clickable @click="setValueForDatetime('bt')">
                      <template #right-icon>
                        <van-radio name="bt" />

                      </template>
                    </van-cell>

                    <van-cell title="大于等于" clickable @click="setValueForDatetime('bteq')">
                      <template #right-icon>
                        <van-radio name="bteq" />

                      </template>
                    </van-cell>

                    <van-cell title="小于" clickable @click="setValueForDatetime('lt')">
                      <template #right-icon>
                        <van-radio name="lt" />
                      </template>
                    </van-cell>

                    <van-cell title="小于等于" clickable @click="setValueForDatetime('lteq')">
                      <template #right-icon>
                        <van-radio name="lteq" />
                      </template>
                    </van-cell>

                  </van-cell-group>
                </van-radio-group>
                <van-radio-group v-model="conditiondata[mainactive].viewcondition_comparison" v-else>
                  <van-cell-group>
                    <van-cell title="包含" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'in'">
                      <template #right-icon>
                        <van-radio name="in" />
                      </template>
                    </van-cell>
                    <van-cell title="不包含" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'notin'">
                      <template #right-icon>
                        <van-radio name="notin" />
                      </template>
                    </van-cell>
                    <van-cell title="等于" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'eq'">
                      <template #right-icon>
                        <van-radio name="eq" />
                      </template>
                    </van-cell>
                    <van-cell v-if="(((idobject == 'dailyreports' || idobject == 'weekreports' || idobject == 'monthreport1') && items[mainactive]['text'] === '负责人') || (idobject == 'activity' && items[mainactive]['text'] === '拜访执行人') || (idobject == 'xhjh' && items[mainactive]['text'] === '负责人') || (idobject == 'xsjhn' && items[mainactive]['text'] === '业务员') || (idobject == 'cptd' && items[mainactive]['text'] === '负责人'))" title="等于参照" clickable @click="setValueForRef('inby')">
                      <template #right-icon>
                        <van-radio name="inby" />
                      </template>
                    </van-cell>
                    <van-cell title="不等于" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'noteq'">
                      <template #right-icon>
                        <van-radio name="noteq" />
                      </template>
                    </van-cell>
                    <van-cell title="空" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'empty'">
                      <template #right-icon>
                        <van-radio name="empty" />
                      </template>
                    </van-cell>
                    <van-cell title="非空" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'notempty'">
                      <template #right-icon>
                        <van-radio name="notempty" />
                      </template>
                    </van-cell>
                  </van-cell-group>
                </van-radio-group>

                <van-field v-model="conditiondata[mainactive].viewcondition_value" placeholder="请输入" />

              </template>
            </van-tree-select>
          </template>
          <div style="background:rgb(244,244,244);height:1vh"></div>
          <div style="padding-top:1vh;padding-left:2vw;padding-bottom:1vh;font-size:14px;">
            <van-radio-group v-model="radiovalue" direction="horizontal">
              <van-radio name="asc" icon-size="14px">升序</van-radio>
              <van-radio name="desc" icon-size="14px">降序</van-radio>
            </van-radio-group>
          </div>
          <input type="button" style="margin:1vw;width:27vw" :class="orderby == condition.viewcondition_field ? 'van-button van-button--primary van-button--small' : 'van-button van-button--default van-button--small'" v-for="condition in conditiondata" :key="condition.index" @click="chooseOrder(condition.viewcondition_field)" :value="condition.viewcondition_title" />
          <div style="background:rgb(244,244,244);height:1vh"></div>
          <button type="button" style="margin:1vw;" v-for="tag in searchtags" @click="chooseTag(tag.id)" :key="tag.id" :class="tag.tagclass.replaceAll('tag-large', 'tag-list')">{{ tag.sname }}<van-icon v-if="!(!searchedtags[tag.id])" name="success" /></button>
          <div style="background:rgb(244,244,244);height:1vh"></div>
          <!-- 不能使用van-button -->
          <input type="button" style="margin:1vw;width:27vw" class="van-button van-button--info van-button--small" value="查询" @click="query" />
          <input type="button" style="margin:1vw;width:27vw" class="van-button van-button--default van-button--small" value="清空" @click="clearquery" />
          <input type="button" style="margin:1vw;width:27vw" class="van-button van-button--default van-button--small" value="关闭" @click="searchshow = false" />
        </form>
      </div>
    </van-popup>

    <van-dropdown-menu style="position: fixed;z-index:1;width:33vw;left:0vw;top:0vh;font-size:14px;">
      <van-dropdown-item v-model="value1" :options="option1" @click.native="query" />
    </van-dropdown-menu>
    <div class="van-dropdown-item" @click="showSearchPopup" style="position:fixed;line-height: 48px;text-align: center; z-index:1;width:33vw;left:33vw;top:0vh;font-size:16px !important; background:rgb(255,255,255);">筛选&nbsp;&nbsp;<van-icon size="20px" name="filter-o" /> </div>

    <div @click="showFormPopup" style="position:fixed;z-index:1;width:33vw;line-height: 48px;text-align:center; left:66vw;top:0vh;font-size:16px !important; background:rgb(255,255,255);">搜索&nbsp;&nbsp; <van-icon size="21px" name="search" /></div>

    <!-- <div style="margin-top:48px;height:10px;background-color:whitesmoke"></div> -->
    <div>&nbsp;</div>

    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">

      <van-list v-model="loading" :finished="finished" finished-text="已加载全部数据" @load="onLoad(false)" style="margin-bottom:8vh;">
        <template>
          <div class="schedule-list">
            <div v-for="(item, index) in schedules" :key="index" class="schedule-item" @click="openCard(item.id)">
              <div class="item-header">
                <div class="purpose">
                  <span class="label"></span>
                  <span>{{ item.purpose }}</span>
                </div>
                <div class="customer-count">
                  <span class="label">客户数量：</span>
                  <span class="count">{{ item.customerCount }}</span>
                </div>
              </div>
              <div class="item-details">
                <div>执行人：{{ item.executor }}</div>
                <div>创建人：{{ item.creator }}</div>
                <div>协访人：{{ item.collaborator }}</div>
              </div>
              <div class="bottom">
                <div class="item-dates">
                  <div>开始时间：{{ item.startDate }}</div>
                  <div>结束时间：{{ item.endDate }}</div>
                  <div class="execution-period">
                    执行周期：{{ item.executionPeriod }}
                  </div>
                </div>
                <div class="item-status">
                  <div class="status-top">
                    <span class="label">状态：</span>
                    <span v-if="item.status == '待审核'" :class="'toaudit'">{{ item.status }}</span>
                    <span v-if="item.status == '执行中'" :class="'doing'">{{ item.status }}</span>
                    <span v-if="item.status == '已结束'" :class="'toaudit'">{{ item.status }}</span>
                    <span v-if="item.status == '未启用'" :class="'toaudit'">{{ item.status }}</span>
                  </div>
                  <div class="tags">
                    <div v-for="(tag, index) in item.tags" :key="index">
                      <span class="tagclass"> {{ tag }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </template>
      </van-list>

    </van-pull-refresh>
    <div class="add-button">
      <button @click="addplan">新增</button>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { Search, List, Cell, PullRefresh, Toast, Tabbar, TabbarItem, Popup, Icon, SwipeCell, Dialog, RadioGroup, Radio, CellGroup, Grid, GridItem, DropdownMenu, DropdownItem, TreeSelect, DatetimePicker, Picker } from 'vant'
import * as dd from 'dingtalk-jsapi'
import qs from 'qs'
import wx from 'weixin-js-sdk'
Vue.use(Search).use(List).use(Cell).use(PullRefresh).use(Toast).use(Tabbar).use(TabbarItem).use(Popup).use(Icon).use(SwipeCell).use(Dialog).use(Radio).use(RadioGroup).use(CellGroup).use(Grid).use(GridItem).use(DropdownMenu).use(DropdownItem).use(TreeSelect).use(DatetimePicker).use(Picker)

export default {
  name: 'jhgllist',
  data () {
    return {
      searchPh: '',
      title: this.$route.query.stitle,
      idobject: this.$route.query.idobject,
      idtemplate: this.$route.query.idtemplate,
      extract: this.$route.query.extract,
      sval: '',
      list: [],
      loading: false,
      finished: false,
      isLoading: false,
      active: 0,
      startline: 1,
      pagecount: 20,
      sdshow: false,
      searchshow: false,
      conditiondata: [],
      isflow: '',
      orderby: '',
      radiovalue: 'desc',
      value1: '',
      option1: [],
      mainactive: 0,
      items: [],
      indexflag: 0,
      sdlist: [],
      minDate: new Date(2020, 0, 1),
      currentDate: new Date(),
      maxDate: this.genMaxDate(),
      showDatePicker: false,
      showOpenRef: false,
      // 区域列表
      depcolumns: [],
      conditionValHidden: '',
      searchtags: [],
      searchedtags: {},
      batop_new: false,
      showForm: false,
      schedules: [
        // {
        // purpose: '药品信息传递',
        // customerCount: 6,
        // executor: '李长峰',
        // creator: '魏老师',
        // collaborator: '魏老师',
        // startDate: '2024年9月1日',
        // endDate: '2024年12月1日',
        // executionPeriod: '每周 周一-周三',
        // status: '待审核',
        // tags: ['周期']
        // }
      ]
    }
  },
  created: function () {
    let _this = this
    document.title = _this.$route.query.stitle
    if (dd.env.platform !== 'notInDingTalk') {
      dd.ready(function () {
        dd.biz.navigation.setTitle({
          title: _this.$route.query.stitle
        })
      })
    }
  },

  beforeRouteUpdate (to, from, next) {
    if (to.path === '/jhgllist') {
      //console.log('form111')
      next('/main')
    }
  },
  beforeRouteLeave (to, form, next) {
    let _this = this
    document.title = _this.$route.query.stitle
    if (dd.env.platform !== 'notInDingTalk') {
      dd.ready(function () {
        dd.biz.navigation.setTitle({
          title: _this.$store.state.crmtitle
        })
      })
    }
    next()
  },
  mounted () {
    // this.onLoad()
    // //console.log('mounted')
    // -32是因为左右padding
    //console.log('count per line', Math.floor((screen.width - 32) * 2 / 3 / 12))
  },
  watch: {
    '$route' () {
      //console.log('list isreload变更', this.$store.state.isreload, this.$route)
      if (this.$store.state.isreload && this.$route.name === 'list') {
        // this.onLoad()
        // this.$store.commit('clearreload')
        // this.loading = false
        this.$router.go(0)
      }
      let _this = this
      if (dd.env.platform !== 'notInDingTalk') {
        dd.ready(function () {
          dd.biz.navigation.setTitle({
            title: _this.$route.query.stitle
          })
        })
      }
    }
  },
  methods: {
    chooseTag (tagid) {
      this.$set(this.searchedtags, tagid, !this.searchedtags[tagid])
      //console.log('tag click', this.searchedtags[tagid], this.searchedtags)
    },
    genMaxDate () {
      let date = new Date()
      date.setFullYear(date.getFullYear() + 50)
      return date
    },
    confirmDate (date) {
      //console.log('date: ' + date)
      let year = date.getFullYear()
      let month = date.getMonth() + 1
      let day = date.getDate()
      this.conditiondata[this.mainactive].viewcondition_value = year + '-' + month + '-' + day
      this.showDatePicker = false
    },
    setValueForDatetime (val) {
      this.conditiondata[this.mainactive].viewcondition_comparison = val
      this.showDatePicker = true
    },
    onConfirmRef (value, index) {
      //console.log(`当前值：${value}, 当前索引：${index}`)
      this.conditiondata[this.mainactive].viewcondition_value = value
      this.showOpenRef = false
    },
    setValueForRef (val) {
      this.conditiondata[this.mainactive].viewcondition_comparison = val
      //console.log('datamodel1:' + JSON.stringify(this.conditiondata[this.mainactive]))

      this.$router.push({
        name: 'idownerMultiForFilter',
        params: {
          valuehidden1: this.conditionValHidden,
          datamodel: this.conditiondata[this.mainactive],
          obj: this
        }
      })
      // this.conditiondata[this.mainactive].viewcondition_comparison = val
      // // 获取列表
      // // alert(this.items[this.mainactive]['text'])
      // this.showOpenRef = true
      // this.axios({
      //   method: 'post',
      //   url: '/api/' + 'dep' + '.list.do'
      // }).then(res => {
      //   //console.log('list res:' + JSON.stringify(res))
      //   let _arr = res.data.jsondata.fieldValue
      //   for (let i = 0; i < _arr.length; i++) {
      //     this.depcolumns.push(_arr[i].dep_sname)
      //   }
      // }).catch(res => {
      //   Toast('获取区域列表异常，请联系管理员！')
      //   //console.log(res)
      // })
      //
      // //console.log('depcolumns:' + this.depcolumns)
    },
    formatter (type, val) {
      if (type === 'year') {
        return `${val}年`
      } else if (type === 'month') {
        return `${val}月`
      }
      return val
    },
    onLoad (clear = true) {
      //console.log('onload')
      let data = {
        'startline': this.startline,
        'pagecount': this.pagecount,
        'condition': this.sval,
        'orderby': this.orderby,
        'ascdesc': this.radiovalue,
        'viewoption': this.value1,
        'extract': this.extract,
        'tags': JSON.stringify(this.searchedtags)
      }
      for (let i = 0; i < this.conditiondata.length; i++) {
        data[i + '_viewcondition_field'] = this.conditiondata[i].viewcondition_field
        data[i + '_viewcondition_relfield'] = this.conditiondata[i].viewcondition_relfield
        data[i + '_viewcondition_value'] = this.conditiondata[i].viewcondition_value
        data[i + '_viewcondition_comparison'] = this.conditiondata[i].viewcondition_comparison
        data[i + '_viewcondition_object'] = this.conditiondata[i].viewcondition_object
        data[i + '_viewcondition_uitype'] = this.conditiondata[i].viewcondition_uitype
      }
      /*
        averageCharWidth=fontSize×0.5（大约值，实际值可能需要调整）
        charsPerLine=averageCharWidth/divWidth
      */
      // data['countperline'] = Math.floor((screen.width - 32) * 2 / 3 / 12)
      //console.log('data:', data)
      /* let templatelength = this.conditiondata.length + 1
      if (this.idtemplate != null && this.idtemplate !== '' && this.idtemplate !== undefined) {
        data[templatelength + '_viewcondition_field'] = 'idtemplate'
        data[templatelength + '_viewcondition_relfield'] = ''
        data[templatelength + '_viewcondition_value'] = this.idtemplate
        data[templatelength + '_viewcondition_comparison'] = 'eqref'
        data[templatelength + '_viewcondition_object'] = ''
      } */

      this.axios({
        method: 'post',
        url: '/api/' + this.idobject + '.list.do',
        data: qs.stringify(data)
      }).then(res => {
        //console.log('list res:', res)
        if (res.data.sdlist) {
          this.sdlist = res.data.sdlist
        }
        if (res.data.batop_new) {
          this.batop_new = res.data.batop_new
          //console.log('this.batop_new == true?', this.batop_new == true)
          //console.log('this.batop_new == false?', this.batop_new == false)
        }
        if (res.data.flag === '1') {
          Toast(res.data.des)
          if (res.data.des && res.data.des.indexOf('登录过期') >= 0) {
            this.loginout()
          }
        } else {
          //console.log('res', res)
          this.isflow = res.data.jsondata.isflow
          let rsdata = res.data.jsondata.fieldValue
          let viewOptions = res.data.viewOptions
          this.value1 = res.data.viewoption
          if (res.data.viewcondition?.length > 0) {
            this.searchPh = res.data.viewcondition.map(i => i.viewcondition_title).join('/')
          }
          //console.log(viewOptions)
          this.option1 = []
          for (let i = 0; i < viewOptions.length; i++) {
            this.option1.push({ text: viewOptions[i][1], value: viewOptions[i][0] })
          }
          this.indexflag = this.list.length
          if (clear) {
            this.schedules = []
          }
          for (let i = 0; i < rsdata.length; i++) {
            // this.list.push(rsdata[i])
            let data = rsdata[i]
            let item = {}
            item.id = data.id
            item.purpose = data.jhgl_mudi
            item.customerCount = data.jhgl_khs
            item.executor = data.jhgl_idowner_ref
            item.creator = data.jhgl_createdby_ref
            item.collaborator = data.jhgl_xiefangby_ref ? data.jhgl_xiefangby_ref : '无'
            item.startDate = this.formatDate(data.jhgl_kssj)
            item.endDate = this.formatDate(data.jhgl_jssj)
            item.executionPeriod = this.formatPeriod(data.jhgl_zqlxpq_enum, data.jhgl_zqlx_enum, data.jhgl_pqz)
            item.status = data.jhgl_status_enum
            item.status_id = data.jhgl_status
            // TODO 路线?
            item.tags = []
            if (data.jhgl_jhscbylx_enum == '路线内') {
              item.tags.push('路线')
            }
            item.tags.push(data.jhgl_zqlx_enum)

            this.schedules.push(item)
          }
          //console.log('this.schedules', this.schedules)

          if (rsdata == null || rsdata.length === 0 || rsdata.length < this.pagecount) {
            this.loading = false
            this.finished = true
          } else {
            this.startline = this.startline + rsdata.length
            this.loading = false
          }
        }
        this.$store.commit('clearreload')
      }).catch(res => {
        this.reserror(res)
      })
    },
    onRefresh () {
      this.list = []
      this.startline = 1
      this.finished = false
      this.loading = true
      this.isLoading = false
      this.onLoad()
    },
    currenttime () {
      let d = new Date()
      let year = d.getFullYear()
      let month = this.change(d.getMonth() + 1)
      let day = this.change(d.getDate())
      let hour = this.change(d.getHours())
      let minute = this.change(d.getMinutes())
      let second = this.change(d.getSeconds())
      let time = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
      return time
    },
    change (t) {
      if (t < 10) {
        return '0' + t
      } else {
        return t
      }
    },
    onSearch () {
      this.list = []
      this.startline = 1
      this.finished = false
      this.loading = true
      this.onLoad()
      this.showForm = false
    },
    onCancel () {
      this.sval = ''
    },
    chooseOrder (value) {
      this.orderby = value
    },
    showPopup () {
      this.sdshow = true
    },
    returnHome () {
      this.$router.push({ name: 'main' })
    },
    showFormPopup () {
      //console.log('form ...')
      this.showForm = true
    },
    showSearchPopup () {
      //console.log('conditiondata:' + this.conditiondata)
      if (this.conditiondata.length === 0) {
        let data = {}
        this.axios({
          method: 'post',
          url: '/api/' + this.idobject + '.query.do',
          data: qs.stringify(data)
        }).then(res => {
          if (res.data.flag === '1') {
            Toast(res.data.des)
            if (res.data.des && res.data.des.indexOf('登录过期') >= 0) {
              this.loginout()
            }
          } else {
            //console.log(res)
            this.searchtags = res.data.tags
            this.conditiondata = res.data.jsondata
            this.items = []
            if (this.conditiondata.length <= 0) {
              Toast('请先在开发平台配置高级查询条件')
              return
            }
            for (let i = 0; i < this.conditiondata.length; i++) {
              //console.log(this.conditiondata[i].viewcondition_title)
              this.items.push({ text: this.conditiondata[i].viewcondition_title })
            }
            this.searchshow = true
          }
        }).catch(res => {
          this.reserror(res)
        })
      } else {
        this.searchshow = true
      }
    },
    query () {
      this.list = []
      this.startline = 1
      this.finished = false
      this.loading = true
      this.searchshow = false
      this.onLoad()
    },
    clearquery () {
      for (let i = 0; i < this.conditiondata.length; i++) {
        this.conditiondata[i].viewcondition_value = ''
      }
      // this.searchshow = false
      this.orderby = ''
    },
    openNew () {
      this.sdshow = false
      if (this.idobject == 'bflx') {
        this.$router.push({
          name: 'bflxnew',
          query: { stitle: this.title, idobject: this.idobject, idtemplate: this.idtemplate }
        })
      } else {
        this.$router.push({
          name: 'new',
          query: { stitle: this.title, idobject: this.idobject, idtemplate: this.idtemplate }
        })
      }
    },
    openCard (itemid) {
      //console.log('itemid:', itemid)

      const schedulesArr = [...this.schedules]
      const item = schedulesArr.find(obj => obj.id === itemid)
      //console.log('item:', item)
      this.$router.push({ name: 'plancard', query: { stitle: '计划管理详情', itemid: itemid, idobject: this.idobject, idtemplate: this.idtemplate, schedules: item } })
    },
    formatDate (dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      const options = { year: 'numeric', month: 'long', day: 'numeric', timeZone: 'Asia/Shanghai' }
      return date.toLocaleDateString('zh-CN', options).replace(/年(\d{1,2})月/, '年$1月').replace(/日$/, '日')
    },
    formatPeriod (pqlx, zqlx, pqz) {
      //console.log(pqlx, zqlx, pqz)
      if (zqlx == '周期') {
        if (pqlx == '按周排期') {
          return '每周 周' + pqz
        }
        return '每月 ' + pqz
      }
      return '无'
    },
    addplan (object) {
      //console.log(`============================ ${this.title} ${this.idobject} ${this.idtemplate}`)
      //console.log(this.jsondata)
      //console.log(this.refCustomers)
      let code = ''
      if (this.jsondata) {
        const details = this.jsondata.Details
        lab: for (let i = 0; details && i < details.length; i++) {
          const groupvalues = details[i].groupvalue
          for (let j = 0; groupvalues && j < groupvalues.length; j++) {
            if (groupvalues[j].sField === 'scode') {
              code = groupvalues[j].value
              break lab
            }
          }
        }
      }
      //console.log('code: ', code)
      /* this.$router.push({
        name: 'plannew',
        query: { stitle: '添加计划', idobject: 'jhgl', idtemplate: this.idtemplate, routetype: '2c9a2d9291db5a1f0191dea23b4d00ec' }
      }) */
      this.$router.push({
        name: 'planscenario',
        query: { stitle: '场景', idtemplate: this.idtemplate }
      })
    }

  },
  activated () {
    // sdshow 特殊处理，后退时没有关闭，原因不明。
    this.sdshow = false
  }
}
</script>

<style scoped>
.schedule-management {
  font-family: Arial, sans-serif;
  background: #f6f6f6;
  min-height: 100vh;
}

.schedule-list {
  margin-top: 40px;
  /* margin-bottom:160px; */
  padding-bottom: 0px;
  box-sizing: border-box;
  /* height: 60%; */
  /* padding: 0 15px; */
}

.schedule-item {
  background-color: white;
  padding: 15px 15px 15px 20px;
  box-sizing: border-box;
  /*margin-bottom: 15px;*/
  border-bottom: 1px solid #e9e9e9;
  /* border-top: 10px solid #e9e9e9; */
}

.item-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 14px;
}

.item-header .purpose {
  font-family: "Microsoft YaHei Bold";
  font-weight: 700;
  font-size: 16px;
  text-align: left;
  color: #000;
}

.item-header .customer-count .label {
  color: #000000;
  font-size: 14px;
  font-face: Microsoft YaHei;
  font-weight: 700;
  letter-spacing: 0;
}

.item-header .customer-count .count {
  color: #000000;
  font-size: 18px;
  font-face: Microsoft YaHei;
  font-weight: 700;
  letter-spacing: 0;
}

.item-details {
  display: flex;
  justify-content: space-between;
  font-family: "Microsoft YaHei";
  font-weight: 400;
  font-size: 14px;
  text-align: left;
  color: #000;
  margin-bottom: 14px;
}

.bottom {
  display: flex;
  justify-content: space-between;
}

.bottom .item-dates {
  /*flex-basis: 220px;*/
}

.bottom .item-dates div {
  font-family: "Microsoft YaHei";
  font-weight: 400;
  font-size: 14px;
  text-align: left;
  color: #818181;
  box-sizing: border-box;
  padding-bottom: 5px;
}

.bottom .item-status {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  /*flex-basis: 225px;*/
}

.bottom .item-status .tags {
  align-self: flex-end;
  display: flex;
  justify-content: space-between;
  padding: 6px 0;
}

.bottom .item-status .tags span {
  margin-left: 3px;
}

.item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-status .status-top {
  text-align: right;
}

.toaudit {
  color: #ee8700;
  font-size: 14px;
  font-face: Microsoft YaHei;
  font-weight: 400;
  letter-spacing: 0;
}

.doing {
  color: #23b400;
  font-size: 14px;
  font-face: Microsoft YaHei;
  font-weight: 400;
  letter-spacing: 0;
}

.item-status .status-top .label {
  color: #000000;
  font-size: 14px;
  font-face: Microsoft YaHei;
  font-weight: 400;
  letter-spacing: 0;
}

.tags .tagclass {
  padding: 3px 10px;
  box-sizing: border-box;
  width: 56px;
  height: 23px;
  border-radius: 11.5px;
  background: #fff4da;
  color: #e9a913;
  font-size: 14px;
}

.status {
  padding: 2px 10px;
  border-radius: 4px;
  font-size: 12px;
}

.status-pending {
  background-color: #fff3cd;
  color: #856404;
}

.status-active {
  background-color: #d4edda;
  color: #155724;
}

.add-button {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 15px 20px;
  background-color: white;
}

.add-button button {
  width: 100%;
  /*background-color: #007bff;*/
  background: #5790df;
  color: white;
  border: none;
  padding: 10px;
  border-radius: 5px;
  font-size: 16px;
}
</style>
